<?php

namespace app\admin\controller;

use app\admin\model\AdminLog;
use app\admin\model\Admin;
use app\admin\model\AuthGroupAccess;
use fast\Random;
use app\common\controller\Backend;
use think\Config;
use think\Hook;
use think\Validate;

use think\Log;

/**
 * 后台首页
 * @internal
 */
class Index extends Backend
{

    protected $noNeedLogin = ['login', 'linelogin', 'reply'];
    protected $noNeedRight = ['index', 'logout'];
    protected $layout = '';

    public function _initialize()
    {
        parent::_initialize();
    }

    /**
     * 后台首页
     */
    public function index()
    {

        //左侧菜单
        list($menulist, $navlist, $fixedmenu, $referermenu) = $this->auth->getSidebar([
            'jdy/news' => ['new'],
            'dashboard' => 'hot',
            'addon' => ['new', 'red', 'badge'],
            'auth/rule' => __('Menu'),
            'general' => ['new', 'purple'],
        ], $this->view->site['fixedpage']);
        $action = $this->request->request('action');
        if ($this->request->isPost()) {
            if ($action == 'refreshmenu') {
                $this->success('', null, ['menulist' => $menulist, 'navlist' => $navlist]);
            }
        }
        $this->view->assign('menulist', $menulist);
        $this->view->assign('navlist', $navlist);
        $this->view->assign('fixedmenu', $fixedmenu);
        $this->view->assign('referermenu', $referermenu);
        $this->view->assign('title', __('Home'));
        return $this->view->fetch();
    }


    //http://wu.test/admin/index/linelogin?code=26JZC9IMhf19CfXVEGSl&state=colin600
    //需要直接登录
    public function linelogin()
    {

        $code = $this->request->request('code', '');
        $state = $this->request->request('state', '');

        if (!empty($code)) {
            $redirect_uri = 'https://' . $_SERVER["HTTP_HOST"] . "/linelogin.php";
            $client_id = "1655262323";
            $client_secret = "1771748f4b1946513ec484d43d21b0d9";

            $payload = "grant_type=authorization_code&client_id=" . $client_id . "&client_secret=" . $client_secret . "&code="
                . $code . "&redirect_uri=" . $redirect_uri;

            echo "linelogin0!";

            Log::write('linelogin0','notice');

            try {
                $ch = curl_init();
                curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/oauth2/v2.1/token');
                curl_setopt($ch, CURLOPT_POST, true);
                curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
                curl_setopt($ch, CURLOPT_HTTPHEADER, [
                    'Content-Type: application/x-www-form-urlencoded'
                ]);
                curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
                curl_setopt($ch, CURLOPT_TIMEOUT, 15);
                $ret = curl_exec($ch);
                $err = curl_error($ch);

                if (FALSE === $ret || !empty($err)) {
                    $errno = curl_errno($ch);
                    $info = curl_getinfo($ch);
                }
                curl_close($ch);

                $ret = json_decode($ret, true);

                if (isset($ret['access_token'])) {
                    $access_token = $ret['access_token'];

                    $ch = curl_init();
                    curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/profile');
                    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
                    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
                    curl_setopt($ch, CURLOPT_HTTPHEADER, [
                        'Authorization: Bearer ' . $access_token
                    ]);
                    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 15);
                    curl_setopt($ch, CURLOPT_TIMEOUT, 15);
                    $ret = curl_exec($ch);
                    $err = curl_error($ch);

                    if (FALSE === $ret || !empty($err)) {
                        $errno = curl_errno($ch);
                        $info = curl_getinfo($ch);
                        $this->error('Line登錄失敗！');
                    } else {

                        Log::write($ret,'notice');

                        $ret = json_decode($ret, true);
                        $password = "123456";
                        // {userId=Ua2b67a5b7ac9d3923a9ec04cc6dc7250; displayName=Miro Lu@TW; pictureUrl=https://profile.line-scdn.net/0h9k2ANZVJZkQPOEzIqZEZEzN9aCl4FmAMd14hKn5qbCRyXShGMl17IH9tMHMiACZHYQ4vdX09bXFy; }
                        // Line第三方登录成功
                        $admin = Admin::where('line_userid', $ret['userId'])->find();
                        if (!$admin) {
                            $username = "Line_" . $ret['userId'];
                            $admin = new Admin();
                            $admin->username = $username;
                            $admin->nickname = $ret['displayName'];
                            $admin->email = $username . "@qq.com";
                            $salt = Random::alnum();
                            $admin->salt = $salt;
                            $admin->line_userid = $ret['userId'];
                            $admin->password = md5(md5($password) . $salt);
                            $admin->avatar = $ret['pictureUrl']; //设置新管理员默认头像。
                            $admin->save();

                            $aga = new AuthGroupAccess();
                            $aga->uid = $admin->id;
                            $aga->group_id = 3;// Line登录账号
                            $aga->save();
                        }

                        $username = $admin->username;

                        $url = "index/index";
                        $result = $this->auth->login($username, $password, 864000);
                        if ($result === true) {
                            $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
                        } else {
                            $msg = $this->auth->getError();
                            $msg = $msg ? $msg : __('Username or password is incorrect');
                            $this->error($msg);
                        }

                    }
                    curl_close($ch);
                }

            } catch (Exception $e) {
                return false;
            }

        } else {
            $this->error('Line登錄失敗！');
        }

        echo "linelogin22!";
    }

    public function reply()
    {
        $input = $this->request->request('__input', '');
        $input = json_decode($input, true);
        if ($input && isset($input['__input'])) {
            $input = $input['__input'];
            $events = $input['events'];
            $event = $events[0];
        }

//colin111={
//__input=
//    {events=
//        {0=
//            {
//                type=message;
//                replyToken=8a68ab4e18db4e91a1fe1d5660df1ed1;
//                source={userId=U5d1f972014b4d493ab74e9d5f8656cd6; type=user; };
//                timestamp=1536815866100;
//                message={type=text; id=8564849950468; text=Tyu; };
//            };
//        };
//    };
//};
        $channelAccessToken = "HsbrN66HA283r4TxyauVJ3tHrvtY09YCzQbVm2SZoP1eF3smjwqJuFCLO6cjA4RkEcYlkxtgpVRmatN9dyKHEWRtSOfTgw1NGCoP3LlXsxFqwnYTH5xZUTY7dxOJ7bN89FxGIy8zL9TpteCjkG55xgdB04t89/1O/w1cDnyilFU=";
        $password = 'mego';      // user login password
        $userId = $event['source']['userId'];

        if ($event['message']['text'] === $password) {
            $message = 'Login Success! Wellcome!';
        } else {
            $message = 'Input password please.';
        }

        $payload = [
            'replyToken' => $event['replyToken'],
            'messages' => [
                [
                    'type' => 'text',
                    'text' => $message
                ]
            ]
        ];

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, 'https://api.line.me/v2/bot/message/reply');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json',
            'Authorization: Bearer ' . $channelAccessToken
        ]);
        $result = curl_exec($ch);
        curl_close($ch);

        echo 'reply';
    }

    /**
     * 管理员登录
     */
    public function login()
    {
        $url = $this->request->get('url', 'index/index');
        if ($this->auth->isLogin()) {
            $this->success(__("You've logged in, do not login again"), $url);
        }

        if ($this->request->isPost()) {
            $username = $this->request->post('username');
            $password = $this->request->post('password');
            $keeplogin = $this->request->post('keeplogin');
            $token = $this->request->post('__token__');
            $rule = [
                'username' => 'require|length:3,30',
                'password' => 'require|length:3,30',
                '__token__' => 'require|token',
            ];
            $data = [
                'username' => $username,
                'password' => $password,
                '__token__' => $token,
            ];
            if (Config::get('fastadmin.login_captcha')) {
                $rule['captcha'] = 'require|captcha';
                $data['captcha'] = $this->request->post('captcha');
            }
            $validate = new Validate($rule, [], ['username' => __('Username'), 'password' => __('Password'), 'captcha' => __('Captcha')]);
            $result = $validate->check($data);
            if (!$result) {
                $this->error($validate->getError(), $url, ['token' => $this->request->token()]);
            }
            AdminLog::setTitle(__('Login'));
            $result = $this->auth->login($username, $password, $keeplogin ? 864000 : 0);
            if ($result === true) {
                Hook::listen("admin_login_after", $this->request);
                $this->success(__('Login successful'), $url, ['url' => $url, 'id' => $this->auth->id, 'username' => $username, 'avatar' => $this->auth->avatar]);
            } else {
                $msg = $this->auth->getError();
                $msg = $msg ? $msg : __('Username or password is incorrect');
                $this->error($msg, $url, ['token' => $this->request->token()]);
            }
        }

        // 根据客户端的cookie,判断是否可以自动登录
        if ($this->auth->autologin()) {
            $this->redirect($url);
        }
        $background = Config::get('fastadmin.login_background');
        $background = stripos($background, 'http') === 0 ? $background : config('site.cdnurl') . $background;
        $this->view->assign('background', $background);
        $this->view->assign('title', __('Login'));
        Hook::listen("admin_login_init", $this->request);

        //http://acciot.test/index/user/login.html
        $registerurl = 'https://' . $_SERVER['HTTP_HOST'] . "/index/user/register.html";
        $this->view->assign('registerurl', $registerurl);


        $lineurl = "https://access.line.me/oauth2/v2.1/authorize?response_type=code&client_id=1655262323&redirect_uri="
            . urlencode('https://' . $_SERVER["HTTP_HOST"] . "/linelogin.php") . "&state=colin600&scope=openid%20profile&nonce=miro";
        $this->view->assign('lineurl', $lineurl);

        return $this->view->fetch();
    }

    /**
     * 注销登录
     */
    public function logout()
    {
        $this->auth->logout();
        Hook::listen("admin_logout_after", $this->request);
        $this->success(__('Logout successful'), 'index/login');
    }

}
